/**
 * 病历管理页面脚本
 */
document.addEventListener('DOMContentLoaded', function() {
    // 初始化页面
    initMedicalRecords();
});

/**
 * 初始化病历管理页面
 */
function initMedicalRecords() {
    // 初始化按钮事件
    initButtons();
    
    // 初始化表格
    loadMedicalRecords();
    
    // 初始化搜索和过滤功能
    initFilters();
}

/**
 * 初始化按钮事件
 */
function initButtons() {
    // 添加病历按钮
    const addRecordBtn = document.getElementById('addRecordBtn');
    if (addRecordBtn) {
        addRecordBtn.addEventListener('click', function() {
            showRecordModal();
        });
    }
    
    // 导出按钮
    const exportBtn = document.getElementById('exportBtn');
    if (exportBtn) {
        exportBtn.addEventListener('click', function() {
            exportMedicalRecords();
        });
    }
    
    // 模态框关闭按钮
    const closeButtons = document.querySelectorAll('.close-btn');
    closeButtons.forEach(button => {
        button.addEventListener('click', function() {
            const modal = this.closest('.modal');
            hideModal(modal);
        });
    });
    
    // 取消按钮
    const cancelRecord = document.getElementById('cancelRecord');
    if (cancelRecord) {
        cancelRecord.addEventListener('click', function() {
            const modal = document.getElementById('recordModal');
            hideModal(modal);
        });
    }
    
    // 保存按钮
    const saveRecord = document.getElementById('saveRecord');
    if (saveRecord) {
        saveRecord.addEventListener('click', function() {
            saveMedicalRecord();
        });
    }
    
    // 打印按钮
    const printRecord = document.getElementById('printRecord');
    if (printRecord) {
        printRecord.addEventListener('click', function() {
            printMedicalRecord();
        });
    }
    
    // 编辑按钮
    const editRecord = document.getElementById('editRecord');
    if (editRecord) {
        editRecord.addEventListener('click', function() {
            const recordId = document.getElementById('viewRecordId').textContent;
            hideModal(document.getElementById('viewRecordModal'));
            showRecordModal(recordId);
        });
    }
    
    // 全选复选框
    const selectAll = document.getElementById('selectAll');
    if (selectAll) {
        selectAll.addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('#medicalRecordsTableBody input[type="checkbox"]');
            checkboxes.forEach(checkbox => {
                checkbox.checked = this.checked;
            });
        });
    }
    
    // 分页按钮
    const paginationButtons = document.querySelectorAll('.pagination-btn, .pagination-number');
    paginationButtons.forEach(button => {
        if (!button.disabled && !button.classList.contains('active')) {
            button.addEventListener('click', function() {
                // 如果是真实场景，这里会处理分页逻辑
                // 模拟实现中只是更新UI
                document.querySelectorAll('.pagination-number').forEach(btn => {
                    btn.classList.remove('active');
                });
                if (this.classList.contains('pagination-number')) {
                    this.classList.add('active');
                }
            });
        }
    });
}

/**
 * 初始化搜索和过滤功能
 */
function initFilters() {
    // 搜索按钮
    const searchBtn = document.getElementById('searchBtn');
    if (searchBtn) {
        searchBtn.addEventListener('click', function() {
            const searchInput = document.getElementById('searchInput');
            if (searchInput) {
                // 在真实场景中，这里会进行AJAX请求
                console.log(`搜索: ${searchInput.value}`);
                // 模拟重新加载数据
                loadMedicalRecords();
            }
        });
    }
    
    // 搜索框回车事件
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                const searchBtn = document.getElementById('searchBtn');
                if (searchBtn) {
                    searchBtn.click();
                }
            }
        });
    }
    
    // 科室过滤器
    const departmentFilter = document.getElementById('departmentFilter');
    if (departmentFilter) {
        departmentFilter.addEventListener('change', function() {
            // 在真实场景中，这里会进行AJAX请求
            console.log(`科室过滤: ${this.value}`);
            // 模拟重新加载数据
            loadMedicalRecords();
        });
    }
    
    // 时间范围过滤器
    const timeRangeFilter = document.getElementById('timeRangeFilter');
    if (timeRangeFilter) {
        timeRangeFilter.addEventListener('change', function() {
            // 在真实场景中，这里会进行AJAX请求
            console.log(`时间范围过滤: ${this.value}`);
            // 模拟重新加载数据
            loadMedicalRecords();
        });
    }
}

/**
 * 加载病历数据
 */
function loadMedicalRecords() {
    // 模拟加载中状态
    const tableBody = document.getElementById('medicalRecordsTableBody');
    if (tableBody) {
        tableBody.innerHTML = '<tr><td colspan="11" class="text-center">正在加载数据...</td></tr>';
        
        // 模拟API请求延迟
        setTimeout(() => {
            // 模拟数据 - 在真实场景中会从API获取
            const records = getMockMedicalRecords();
            
            // 渲染数据
            renderMedicalRecordsTable(records);
        }, 500);
    }
}

/**
 * 渲染病历表格
 * @param {Array} records - 病历记录数组
 */
function renderMedicalRecordsTable(records) {
    const tableBody = document.getElementById('medicalRecordsTableBody');
    if (!tableBody) return;
    
    if (records.length === 0) {
        tableBody.innerHTML = '<tr><td colspan="11" class="text-center">暂无数据</td></tr>';
        return;
    }
    
    let html = '';
    
    records.forEach(record => {
        const statusClass = record.status === 'DRAFT' ? 'draft' : 
                           record.status === 'ACTIVE' ? 'active' : 'archived';
        const statusText = record.status === 'DRAFT' ? '草稿' : 
                          record.status === 'ACTIVE' ? '有效' : '已归档';
        
        html += `
            <tr>
                <td><input type="checkbox" class="record-checkbox" data-id="${record.id}"></td>
                <td>${record.id}</td>
                <td>${record.patientName}</td>
                <td>${record.patientId}</td>
                <td>${record.doctorName}</td>
                <td>${record.department}</td>
                <td>${record.diagnosis}</td>
                <td>${formatDate(record.visitDate)}</td>
                <td>${formatDate(record.updateTime)}</td>
                <td><span class="status-badge ${statusClass}">${statusText}</span></td>
                <td>
                    <div class="action-buttons">
                        <button class="action-btn view" data-id="${record.id}" title="查看">
                            <span data-icon="eye"></span>
                        </button>
                        <button class="action-btn edit" data-id="${record.id}" title="编辑">
                            <span data-icon="edit"></span>
                        </button>
                        <button class="action-btn delete" data-id="${record.id}" title="删除">
                            <span data-icon="trash"></span>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    });
    
    tableBody.innerHTML = html;
    
    // 添加操作按钮事件
    addTableActionEvents();
}

/**
 * 添加表格操作按钮事件
 */
function addTableActionEvents() {
    // 查看按钮
    const viewButtons = document.querySelectorAll('.action-btn.view');
    viewButtons.forEach(button => {
        button.addEventListener('click', function() {
            const recordId = this.getAttribute('data-id');
            viewMedicalRecord(recordId);
        });
    });
    
    // 编辑按钮
    const editButtons = document.querySelectorAll('.action-btn.edit');
    editButtons.forEach(button => {
        button.addEventListener('click', function() {
            const recordId = this.getAttribute('data-id');
            showRecordModal(recordId);
        });
    });
    
    // 删除按钮
    const deleteButtons = document.querySelectorAll('.action-btn.delete');
    deleteButtons.forEach(button => {
        button.addEventListener('click', function() {
            const recordId = this.getAttribute('data-id');
            confirmDeleteRecord(recordId);
        });
    });
}

/**
 * 显示病历编辑模态框
 * @param {string} recordId - 病历ID，如果是新增则为空
 */
function showRecordModal(recordId = null) {
    const modal = document.getElementById('recordModal');
    const modalTitle = document.getElementById('modalTitle');
    const form = document.getElementById('recordForm');
    
    if (recordId) {
        // 编辑模式
        modalTitle.textContent = '编辑病历';
        
        // 模拟从API获取数据
        const record = findRecordById(recordId);
        
        if (record) {
            // 填充表单
            document.getElementById('recordId').value = record.id;
            
            // 模拟选择下拉框选项
            const patientSelect = document.getElementById('patientSelect');
            if (patientSelect) {
                // 清空并添加选项
                patientSelect.innerHTML = `
                    <option value="">请选择患者</option>
                    <option value="${record.patientId}" selected>${record.patientName}</option>
                `;
            }
            
            const doctorSelect = document.getElementById('doctorSelect');
            if (doctorSelect) {
                // 清空并添加选项
                doctorSelect.innerHTML = `
                    <option value="">请选择医生</option>
                    <option value="${record.doctorId}" selected>${record.doctorName}</option>
                `;
            }
            
            // 设置科室选项
            const departmentSelect = document.getElementById('departmentSelect');
            if (departmentSelect) {
                const options = departmentSelect.options;
                for (let i = 0; i < options.length; i++) {
                    if (options[i].textContent === record.department) {
                        departmentSelect.selectedIndex = i;
                        break;
                    }
                }
            }
            
            // 设置日期
            const visitDateInput = document.getElementById('visitDate');
            if (visitDateInput) {
                visitDateInput.value = formatDateForInput(record.visitDate);
            }
            
            const followUpDateInput = document.getElementById('followUpDate');
            if (followUpDateInput && record.followUpDate) {
                followUpDateInput.value = formatDateForInput(record.followUpDate);
            }
            
            // 设置文本域
            document.getElementById('symptoms').value = record.symptoms;
            document.getElementById('diagnosis').value = record.diagnosis;
            document.getElementById('treatment').value = record.treatment;
            document.getElementById('notes').value = record.notes || '';
            
            // 设置状态
            const statusSelect = document.getElementById('recordStatus');
            if (statusSelect) {
                statusSelect.value = record.status;
            }
        }
    } else {
        // 新增模式
        modalTitle.textContent = '添加新病历';
        
        // 重置表单
        if (form) {
            form.reset();
            document.getElementById('recordId').value = '';
        }
        
        // 初始化患者和医生下拉框
        initPatientAndDoctorSelects();
        
        // 设置默认日期为今天
        const visitDateInput = document.getElementById('visitDate');
        if (visitDateInput) {
            visitDateInput.value = formatDateForInput(new Date());
        }
        
        // 设置默认状态为草稿
        const statusSelect = document.getElementById('recordStatus');
        if (statusSelect) {
            statusSelect.value = 'DRAFT';
        }
    }
    
    // 显示模态框
    showModal(modal);
}

/**
 * 初始化患者和医生下拉框
 */
function initPatientAndDoctorSelects() {
    // 模拟获取患者列表
    const patients = [
        { id: '1', name: '张三' },
        { id: '2', name: '李四' },
        { id: '3', name: '王五' }
    ];
    
    // 模拟获取医生列表
    const doctors = [
        { id: '1', name: '王医生' },
        { id: '2', name: '李医生' },
        { id: '3', name: '张医生' }
    ];
    
    // 填充患者下拉框
    const patientSelect = document.getElementById('patientSelect');
    if (patientSelect) {
        let options = '<option value="">请选择患者</option>';
        patients.forEach(patient => {
            options += `<option value="${patient.id}">${patient.name}</option>`;
        });
        patientSelect.innerHTML = options;
    }
    
    // 填充医生下拉框
    const doctorSelect = document.getElementById('doctorSelect');
    if (doctorSelect) {
        let options = '<option value="">请选择医生</option>';
        doctors.forEach(doctor => {
            options += `<option value="${doctor.id}">${doctor.name}</option>`;
        });
        doctorSelect.innerHTML = options;
    }
}

/**
 * 保存病历记录
 */
function saveMedicalRecord() {
    // 获取表单数据
    const form = document.getElementById('recordForm');
    if (!form) return;
    
    // 简单的表单验证
    const required = form.querySelectorAll('[required]');
    let isValid = true;
    
    required.forEach(field => {
        if (!field.value.trim()) {
            isValid = false;
            field.classList.add('invalid');
        } else {
            field.classList.remove('invalid');
        }
    });
    
    if (!isValid) {
        showToast('请填写所有必填字段', 'error');
        return;
    }
    
    // 收集表单数据
    const formData = {
        id: document.getElementById('recordId').value,
        patientId: document.getElementById('patientSelect').value,
        patientName: document.getElementById('patientSelect').options[document.getElementById('patientSelect').selectedIndex].text,
        doctorId: document.getElementById('doctorSelect').value,
        doctorName: document.getElementById('doctorSelect').options[document.getElementById('doctorSelect').selectedIndex].text,
        departmentId: document.getElementById('departmentSelect').value,
        department: document.getElementById('departmentSelect').options[document.getElementById('departmentSelect').selectedIndex].text,
        visitDate: document.getElementById('visitDate').value,
        followUpDate: document.getElementById('followUpDate').value,
        symptoms: document.getElementById('symptoms').value,
        diagnosis: document.getElementById('diagnosis').value,
        treatment: document.getElementById('treatment').value,
        status: document.getElementById('recordStatus').value,
        notes: document.getElementById('notes').value,
    };
    
    // 在真实场景中，这里会进行AJAX请求保存数据
    console.log('保存病历数据:', formData);
    
    // 模拟保存成功
    showToast('保存成功', 'success');
    
    // 关闭模态框
    hideModal(document.getElementById('recordModal'));
    
    // 重新加载数据
    loadMedicalRecords();
}

/**
 * 查看病历详情
 * @param {string} recordId - 病历ID
 */
function viewMedicalRecord(recordId) {
    // 模拟从API获取数据
    const record = findRecordById(recordId);
    
    if (!record) {
        showToast('找不到病历记录', 'error');
        return;
    }
    
    // 填充详情模态框
    document.getElementById('viewRecordId').textContent = record.id;
    
    // 设置状态标签
    const statusElement = document.getElementById('viewRecordStatus');
    const statusClass = record.status === 'DRAFT' ? 'draft' : 
                       record.status === 'ACTIVE' ? 'active' : 'archived';
    const statusText = record.status === 'DRAFT' ? '草稿' : 
                      record.status === 'ACTIVE' ? '有效' : '已归档';
    statusElement.className = 'record-status ' + statusClass;
    statusElement.textContent = statusText;
    
    // 设置基本信息
    document.getElementById('viewPatientName').textContent = record.patientName;
    document.getElementById('viewPatientId').textContent = record.patientId;
    document.getElementById('viewDoctorName').textContent = record.doctorName;
    document.getElementById('viewDepartment').textContent = record.department;
    document.getElementById('viewVisitDate').textContent = formatDate(record.visitDate);
    
    if (record.followUpDate) {
        document.getElementById('viewFollowUpDate').textContent = formatDate(record.followUpDate);
    } else {
        document.getElementById('viewFollowUpDate').textContent = '无';
    }
    
    // 设置内容
    document.getElementById('viewSymptoms').textContent = record.symptoms;
    document.getElementById('viewDiagnosis').textContent = record.diagnosis;
    document.getElementById('viewTreatment').textContent = record.treatment;
    document.getElementById('viewNotes').textContent = record.notes || '无';
    
    // 设置时间戳
    document.getElementById('viewCreateTime').textContent = formatDateTime(record.createTime);
    document.getElementById('viewUpdateTime').textContent = formatDateTime(record.updateTime);
    
    // 显示模态框
    showModal(document.getElementById('viewRecordModal'));
}

/**
 * 确认删除病历
 * @param {string} recordId - 病历ID
 */
function confirmDeleteRecord(recordId) {
    if (confirm(`确定要删除ID为 ${recordId} 的病历记录吗？`)) {
        // 在真实场景中，这里会进行AJAX请求删除数据
        console.log(`删除病历: ${recordId}`);
        
        // 模拟删除成功
        showToast('删除成功', 'success');
        
        // 重新加载数据
        loadMedicalRecords();
    }
}

/**
 * 导出病历记录
 */
function exportMedicalRecords() {
    // 在真实场景中，这里会调用API导出数据
    showToast('病历记录导出中...', 'info');
    
    // 模拟导出延迟
    setTimeout(() => {
        showToast('导出成功', 'success');
    }, 1500);
}

/**
 * 打印病历记录
 */
function printMedicalRecord() {
    // 在真实场景中，这里会调用打印功能
    showToast('准备打印...', 'info');
    
    // 模拟打印
    setTimeout(() => {
        window.print();
    }, 500);
}

/**
 * 显示模态框
 * @param {HTMLElement} modal - 模态框元素
 */
function showModal(modal) {
    if (modal) {
        modal.classList.add('visible');
        document.body.classList.add('modal-open');
    }
}

/**
 * 隐藏模态框
 * @param {HTMLElement} modal - 模态框元素
 */
function hideModal(modal) {
    if (modal) {
        modal.classList.remove('visible');
        document.body.classList.remove('modal-open');
    }
}

/**
 * 显示消息提示
 * @param {string} message - 提示消息
 * @param {string} type - 提示类型 (success, error, info, warning)
 */
function showToast(message, type = 'info') {
    // 检查是否已存在toast容器
    let toastContainer = document.querySelector('.toast-container');
    
    if (!toastContainer) {
        toastContainer = document.createElement('div');
        toastContainer.classList.add('toast-container');
        document.body.appendChild(toastContainer);
    }
    
    // 创建toast元素
    const toast = document.createElement('div');
    toast.classList.add('toast', `toast-${type}`);
    
    // 创建图标
    const icon = document.createElement('span');
    icon.setAttribute('data-icon', type === 'success' ? 'check-circle' : 
                               type === 'error' ? 'alert-circle' : 
                               type === 'warning' ? 'alert-triangle' : 'info');
    
    // 创建消息文本
    const text = document.createElement('span');
    text.textContent = message;
    
    // 添加到toast
    toast.appendChild(icon);
    toast.appendChild(text);
    
    // 添加到容器
    toastContainer.appendChild(toast);
    
    // 显示动画
    setTimeout(() => {
        toast.classList.add('show');
    }, 10);
    
    // 自动消失
    setTimeout(() => {
        toast.classList.remove('show');
        
        // 动画完成后移除元素
        setTimeout(() => {
            toast.remove();
            
            // 如果没有更多toast，移除容器
            if (toastContainer.children.length === 0) {
                toastContainer.remove();
            }
        }, 300);
    }, 3000);
}

/**
 * 格式化日期 (yyyy-MM-dd)
 * @param {string|Date} date - 日期字符串或Date对象
 * @returns {string} 格式化后的日期字符串
 */
function formatDate(date) {
    if (!date) return '';
    
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
}

/**
 * 格式化日期时间 (yyyy-MM-dd HH:mm:ss)
 * @param {string|Date} datetime - 日期时间字符串或Date对象
 * @returns {string} 格式化后的日期时间字符串
 */
function formatDateTime(datetime) {
    if (!datetime) return '';
    
    const d = new Date(datetime);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    const hours = String(d.getHours()).padStart(2, '0');
    const minutes = String(d.getMinutes()).padStart(2, '0');
    const seconds = String(d.getSeconds()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

/**
 * 格式化日期为input元素的value格式 (yyyy-MM-dd)
 * @param {string|Date} date - 日期字符串或Date对象
 * @returns {string} 格式化后的日期字符串
 */
function formatDateForInput(date) {
    if (!date) return '';
    
    const d = new Date(date);
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    
    return `${year}-${month}-${day}`;
}

/**
 * 根据ID查找病历记录
 * @param {string} id - 病历ID
 * @returns {Object|null} 病历记录对象或null
 */
function findRecordById(id) {
    const records = getMockMedicalRecords();
    return records.find(record => record.id === id) || null;
}

/**
 * 获取模拟病历数据
 * @returns {Array} 病历记录数组
 */
function getMockMedicalRecords() {
    return [
        {
            id: 'MR10001',
            patientId: '1',
            patientName: '张三',
            doctorId: '1',
            doctorName: '王医生',
            departmentId: '1',
            department: '内科',
            visitDate: '2023-06-15',
            followUpDate: '2023-07-15',
            symptoms: '患者自述头痛、乏力3天，伴有轻微发热，体温37.8℃，无恶心呕吐。',
            diagnosis: '普通感冒',
            treatment: '1. 口服布洛芬缓释胶囊，每次1粒，每日2次。\n2. 口服维生素C片，每次1片，每日3次。\n3. 注意休息，多饮水。',
            status: 'ACTIVE',
            notes: '患者对青霉素过敏',
            createTime: '2023-06-15 09:30:00',
            updateTime: '2023-06-15 10:15:00'
        },
        {
            id: 'MR10002',
            patientId: '2',
            patientName: '李四',
            doctorId: '2',
            doctorName: '李医生',
            departmentId: '2',
            department: '外科',
            visitDate: '2023-06-16',
            followUpDate: null,
            symptoms: '右手拇指被刀划伤，伤口长约2cm，深约0.5cm，有少量出血。',
            diagnosis: '右手拇指开放性创伤',
            treatment: '1. 伤口清创、缝合。\n2. 口服头孢克洛胶囊，每次1粒，每日3次。\n3. 伤口保持干燥，3天后复诊拆线。',
            status: 'ACTIVE',
            notes: '',
            createTime: '2023-06-16 14:20:00',
            updateTime: '2023-06-16 14:45:00'
        },
        {
            id: 'MR10003',
            patientId: '3',
            patientName: '王五',
            doctorId: '3',
            doctorName: '张医生',
            departmentId: '3',
            department: '儿科',
            visitDate: '2023-06-17',
            followUpDate: '2023-06-24',
            symptoms: '咳嗽、流涕2天，伴有发热，最高体温38.5℃，食欲下降。',
            diagnosis: '上呼吸道感染',
            treatment: '1. 口服小儿氨酚黄那敏颗粒，每次1包，每日3次。\n2. 雾化吸入布地奈德混悬液，每次1支，每日2次。\n3. 多休息，多饮水，密切观察体温变化。',
            status: 'DRAFT',
            notes: '患儿有哮喘病史',
            createTime: '2023-06-17 10:05:00',
            updateTime: '2023-06-17 10:30:00'
        },
        {
            id: 'MR10004',
            patientId: '1',
            patientName: '张三',
            doctorId: '1',
            doctorName: '王医生',
            departmentId: '1',
            department: '内科',
            visitDate: '2023-05-20',
            followUpDate: null,
            symptoms: '反复头痛1个月，疼痛位于额部和颞部，呈胀痛，伴有恶心。血压测量：150/95mmHg。',
            diagnosis: '原发性高血压',
            treatment: '1. 口服厄贝沙坦片，每次1片，每日1次。\n2. 低盐低脂饮食，戒烟限酒。\n3. 每日监测血压，记录血压变化。',
            status: 'ARCHIVED',
            notes: '',
            createTime: '2023-05-20 09:15:00',
            updateTime: '2023-05-20 09:40:00'
        },
        {
            id: 'MR10005',
            patientId: '2',
            patientName: '李四',
            doctorId: '2',
            doctorName: '李医生',
            departmentId: '5',
            department: '神经科',
            visitDate: '2023-06-10',
            followUpDate: '2023-06-17',
            symptoms: '夜间睡眠障碍2周，入睡困难，易醒，伴有情绪低落、乏力。',
            diagnosis: '失眠症',
            treatment: '1. 口服艾司唑仑片，每次1片，睡前30分钟服用。\n2. 建立规律作息，避免午睡和睡前饮用咖啡、茶等。\n3. 必要时心理咨询。',
            status: 'ACTIVE',
            notes: '患者有轻度抑郁倾向',
            createTime: '2023-06-10 16:00:00',
            updateTime: '2023-06-10 16:25:00'
        }
    ];
} 